﻿(function () {
    var
        $mapTipMsg = $('#mapTipMsg'),
	    $txtAddress = $('#txtAddress');

    var MapZoom = 20;/*店铺定位后地图缩放大小*/

    /*当前店铺坐标*/
    var curLocation,
        myGeo,
        options,
        cacheMapData,
        map,
        marker,
        isSignMaping = false;

    var api = {},
        defauls = {
            "MapCity": "深圳",
            "MapZoom": 15,
            "FromType": 0,
            "ReturnUrl": null,
            "ChangeLocationBtnText": "修改地图位置"
        };
    ;

    function fnTipMsg(msg) {
        alert(msg);
    }

    function Debug(obj) {
        window['console'] && console.log(obj);
    }

    String.prototype.formatWith = function () {
        var args = arguments, self = this;;
        for (var i = 0, len = args.length; i < len; i++) {
            self = self.replace(new RegExp('\\{' + i + '\\}', 'g'), args[i]);
        }
        return self;
    };

    api.saveCurLoc = function () {
        if (!curLocation) {
            return fnTipMsg('参数错误！');
        }
        var saveData = { lat: curLocation.lat, lng: curLocation.lng, t: Math.random(), address: options.Address };
        var data = mapCommon.callback(options, saveData);
        if ($.isPlainObject(data)) {
            if (data.errorCode === 0) {
                fnTipMsg(data.msg || '保存成功');
            } else {
                fnTipMsg(data.msg || '保存失败');
            }
        }
    };

    api.changeShopMapLoc = function (shopId) {
        fnSetSignStatus(true);
        map.setZoom(15);
        map.clearOverlays();
    };

    /*切换地图是否正在标记状态*/
    function fnSetSignStatus(isSigning) {
        $mapTipMsg.text('点击地图即标注位置').toggle(isSigning);
        isSignMaping = isSigning;
    }

    api.init = function (opts) {
        options = $.extend(true, {}, defauls, opts);
        cacheMapData = options.MapData || [];
        map = new BMap.Map("allmap");
        myGeo = new BMap.Geocoder();
        map.addEventListener("click", function (r) {
            Debug(arguments);
            if (isSignMaping) {
                myGeo.getLocation(r.point, function (rs) {
                    Debug(arguments)
                    options.Address = rs.address;
                    signLocation(r.point);
                });
            }
        });
        map.enableScrollWheelZoom();
        var top_right_navigation = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_SMALL });
        map.addControl(top_right_navigation);
        $('#btnSearch').click(searchMapAddress);
        $txtAddress.keyup(function (e) {
            if (e.keyCode == 13) {
                searchMapAddress();
            }
        });
        if (options.Loc) {
            var loc = new BMap.Point(options.Loc.lng, options.Loc.lat);
            signLocation(loc);
        } else {
            map.centerAndZoom(options.MapCity, options.MapZoom);
            searchMapAddress();
        }
    };

    function searchMapAddress() {
        var v = $.trim($txtAddress.val());
        var city = options.MapCity;
        v.length && myGeo.getPoint(v, function (point) {
            fnSetSignStatus(false);
            Debug(arguments);
            if (point) {
                options.Address = v;
                signLocation(point);
            } else {
                map.clearOverlays();
                map.centerAndZoom(city, 12);
                alert("没有搜索到位置，请修改地址重新搜索!");
            }
        }, city);
    }

    function signLocation(point) {
        map.clearOverlays();
        point = new BMap.Point(point.lng, point.lat);
        curLocation = point;
        map.centerAndZoom(point, MapZoom);
        marker = new BMap.Marker(point); // 创建点
        map.addOverlay(marker);
        var content = options.Address; 
        content += '<p class="btns">';
        if (!isSignMaping) {
        content += '<a href="javascript:;" onclick="getAddressMapLocApi.changeShopMapLoc()">修改地图位置</a>';
        }
        content += '<a href="javascript:;" onclick="getAddressMapLocApi.saveCurLoc()">保存当前地图位置</a></p>';
        var infoWindow = new BMap.InfoWindow(content, { offset: new BMap.Size(0, -20) });  // 创建信息窗口对象
        map.openInfoWindow(infoWindow, point);
        marker.addEventListener('click', function () {
            map.openInfoWindow(infoWindow, point);
        });
    }

    window.getAddressMapLocApi = api;
})();